﻿using System.Reflection;
using Gateway.Common.Extensions;

namespace Gateway.Common.Entity
{
    public class EntityBase : IEntityBase
    {
        public virtual string Id { get; protected set; } // = StringExtensions.GetSnowFlakeIdString();

        public EntityBase()
        {
            var tableFileIdAttribute = this.GetType().GetCustomAttribute<PrimaryIdAttribute>();
            if (tableFileIdAttribute == null)
            {
                Id = StringExtensions.GetSnowFlakeIdString();
            }
            else
            {
                Id = (tableFileIdAttribute.Prefix) + StringExtensions.GetSnowFlakeIdString();
            }
        }
        // private string _id;

        // public virtual string Id
        // {
        //     get => _id;
        //     protected set
        //     {
        //         var tableFileIdAttribute = this.GetType().GetCustomAttribute<TableFileIdAttribute>();
        //         if (tableFileIdAttribute == null)
        //         {
        //             _id = StringExtensions.GetSnowFlakeIdString();
        //         }
        //         else
        //         {
        //             _id = (tableFileIdAttribute.Prefix) + StringExtensions.GetSnowFlakeIdString();
        //         }
        //     }
        // }

        public override bool Equals(object? obj)
        {
            var compareTo = obj as EntityBase;

            if (ReferenceEquals(this, compareTo)) return true;
            if (ReferenceEquals(null, compareTo)) return false;

            return Id.Equals(compareTo.Id);
        }

        public static bool operator ==(EntityBase? a, EntityBase b)
        {
            if (ReferenceEquals(a, null) && ReferenceEquals(b, null))
                return true;

            if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
                return false;

            return a.Equals(b);
        }

        public static bool operator !=(EntityBase a, EntityBase b)
        {
            return !(a == b);
        }

        public override int GetHashCode()
        {
            return (GetType().GetHashCode() * 907) + Id.GetHashCode();
        }

        public override string ToString()
        {
            return GetType().Name + " [Id=" + Id + "]";
        }
    }
}